package mest.controller.system;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mest.service.system.UserService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import mest.entity.User;

import mest.util.ObjectUtil;
import mest.util.RedisUtil;
import mest.util.ResultObj;

/**
 * @author Twinson Wong
 * @Title LoginController.java
 * @description TODO
 * @time 2019年12月5日 上午11:53:56
 **/
@RestController
@CrossOrigin
@RequestMapping(value = "/login")
public class LoginController {

    @Resource
    UserService loginService;

    @Resource
    private RedisUtil redisUtil;

    @PostMapping(value = "/loging")
    public ResultObj login(@RequestBody JSONObject jsonObject, HttpServletRequest request, HttpServletResponse response) {
        try {
            User user = jsonObject.toJavaObject(User.class);

            //前端加密了
            //String md5DigestAsHex = DigestUtils.md5DigestAsHex("qwe".getBytes());

            user = loginService.selectAllItem(user);

            if (user == null) {
                return ResultObj.createErrorMsg("用户不存在");
            }
            if (!user.getPassword().equals(jsonObject.get("password"))) {
                return ResultObj.createErrorMsg("密码错误");
            }
            user.setUserId(null);
            User user2 = loginService.selectUser(user);
            HttpSession session = request.getSession();
            session.setAttribute("user", user2);
            return ResultObj.createSuccess(ResultObj.LOGIN_SUCCESS,user);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.createErrorMsg(ResultObj.ERROR2);
        }
    }

    @RequestMapping(value = "/logout")
    public ResultObj logout(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        try {
            User user = jsonObject.toJavaObject(User.class);
            HttpSession session = request.getSession();
            session.invalidate();
            return ResultObj.createSuccessMsg(ResultObj.LOGIN_SUCCESS);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return ResultObj.createErrorMsg(ResultObj.ERROR2);
        }
    }

}
